var newUser;
'use strict';
var app = angular.module('mainApp', [
        'utils',
        'ngRoute',
        'ngCookies',
        'ngResource',
        'ngSanitize',
        'ui.bootstrap',
        'MyDirectives',
        'angularify.semantic',
        //'ngAnimate'
        ]);

var semApp = angular.module('semanticApp', [
        'utils',
        'ngRoute',
        'ngCookies',
        'ngResource',
        'ngSanitize',
//        'ui.bootstrap',
        'MyDirectives',
        'angularify.semantic',
        //'ngAnimate'
        ]);
/*
angular.element(document).ready(function() {
    console.log("document ready")
    //angular.bootstrap(document, ['mainApp']);
  $.get('/auth/user', function(data) {
    newUser = data;
    //angular.bootstrap(document, ['mainApp']);
  });
});
*/

    /*
app.run(function(auth) {
    console.log("app run");
  $.get('/auth/user', function(data) {
      auth.setUser(newUser);
  });
});
  */


app.factory('auth', function ($rootScope) {
    var user = null;

    var map = $rootScope.auth= {
        setUser: function(newUser){
            if(newUser == 'null' || newUser == '<nil>'){
                newUser = undefined;
            }
            console.log("set user" + newUser)
            //set new user to the factory
            //user = JSON.parse(newUser);
            user = newUser;
            $rootScope.$broadcast('userChanged');
        },
        getUser: function(){
            return user;
        },
        hasRole: function(role){
            //console.log("hasRole")
        if(user != null && (typeof user == 'object')){
            return user.Roles.indexOf(role) > -1;
        }
        return false;
    }
   };

    $.get('/auth/user', function(data) {
        map.setUser(data);
  });

    return map;
  });

app.config(['$routeProvider','$interpolateProvider', function( $routeProvider, $interpolateProvider){
    $routeProvider.
    when("/template",{
        templateUrl: "part/template.html",
        controller: "templateCtrl"}).
    when("/main",{
        templateUrl: "part/main.html",
        controller: "mainCtrl"}).
    when("/login",{
        templateUrl: "part/login.html",
        controller: "userCtrl"}).
    when("/orgs",{
        templateUrl: "part/orgs.html",
        controller: "adminCtrl"}).
    when("/blog",{
        templateUrl: "view/blog",
        controller: "blogCtrl"}).
    when("/admin",{
        templateUrl: "view/admin",
        controller: "adminCtrl"}).
    otherwise({
        redirectTo: "/main"
    });
    /*
    */
    $interpolateProvider.startSymbol('[[');
    $interpolateProvider.endSymbol(']]');
}]);


app.service('socket', function($rootScope){
    var socket = io.connect();
    this.on= function (eventName, callback) {
      socket.on(eventName, function () {  
        var args = arguments;
        $rootScope.$apply(function () {
          callback.apply(socket, args);
        });
      });
    }
    this.emit= function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments;
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args);
          }
        });
      })
    }
});


/* sample directive
app.directive('hasPermission', function(auth) {
  return {
    link: function(scope, element, attrs) {
      if(!_.isString(attrs.hasPermission))
        throw "hasPermission value must be a string";
 
      var value = attrs.hasPermission.trim();
      var notPermissionFlag = value[0] === '!';
      if(notPermissionFlag) {
        value = value.slice(1).trim();
      }
 
      function toggleVisibilityBasedOnPermission() {
        var hasPermission = auth.hasPermission(value);
 
        if(hasPermission && !notPermissionFlag || !hasPermission && notPermissionFlag){
          element.show();
          }else{
          element.hide();}
      }
      toggleVisibilityBasedOnPermission();
      scope.$on('permissionsChanged', toggleVisibilityBasedOnPermission);
    }
  };
});
*/
app.directive('myTest', function(auth){
    var roles;
    if(auth.getUser()){
        roles = auth.getUser().roles;
    }

return {
    link: function(scope, element, attrs){
        element.addClass('active');
        element.text('Roles: ' + roles);
        element.append($('<div>').text('embedded div'));

    }
}
});

app.directive('delComment', function(auth){
return {
    link: function(scope, element, attrs){
        var postComment = attrs['delComment'].split(','); //[postId, commentIndex]
        var postId = postComment[0], email = postComment[1];
        var comment = scope.findComment(postComment[0], postComment[1]);

        function toggleElement(){
            //scope.homePosts
            if(comment && auth.getUser()){
                if(auth.getUser()){
                    if(comment.email == auth.getUser().email){
                        element.show();
                    }else{
                        element.hide();
                    }
                }
            }else{
                        element.hide();
            }
        }//toggleElement

        scope.$on('permissionChanged', toggleElement);
        toggleElement();

    }//link
}
});
